package cn.yotta.user.web.autoconfiguration.provider.impl;

import cn.yotta.user.api.params.user.UserFindByTokenRequest;
import cn.yotta.user.api.vo.UserVo;
import cn.yotta.user.web.autoconfiguration.exception.UserLoginException;
import cn.yotta.user.web.autoconfiguration.provider.LoginUser;
import cn.yotta.user.web.autoconfiguration.provider.UserReadFromTokenProvider;

import java.util.Objects;

/**
 * @author w_etw
 * @date 2023/4/15 09:51
 */
public abstract class AbstractYottaUserReadProvider implements UserReadFromTokenProvider {

    @Override
    public LoginUser findUserByToken(String token) throws UserLoginException {
        UserFindByTokenRequest request = buildUserFindByTokenRequest(token);
        UserVo userVo = doFindUserByToken(request);
        return convertToLoginUser(userVo);
    }

    protected UserFindByTokenRequest buildUserFindByTokenRequest(String token) {
        UserFindByTokenRequest request = new UserFindByTokenRequest();
        request.setToken(token);
        return request;
    }
    protected LoginUser convertToLoginUser(UserVo userByToken) {
        if (Objects.isNull(userByToken)) {
            return null;
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setId(userByToken.getId());
        loginUser.setUsername(userByToken.getUsername());
        loginUser.setNickname(userByToken.getNickname());
        loginUser.setRealName(userByToken.getRealName());
        loginUser.setAvatar(userByToken.getAvatar());
        loginUser.setMobile(userByToken.getMobile());
        loginUser.setEmail(userByToken.getEmail());
        loginUser.setEnabled(userByToken.getEnabled());
        loginUser.setLocked(userByToken.getLocked());
        loginUser.setDeleted(userByToken.getDeleted());
        loginUser.setCreatedAt(userByToken.getCreatedAt());
        loginUser.setUpdatedAt(userByToken.getUpdatedAt());
        loginUser.setTenantId(userByToken.getTenantId());
        return loginUser;
    }
    protected abstract UserVo doFindUserByToken(UserFindByTokenRequest findByTokenRequest);
}
